/*******************************************************************************
 * Copyright 2011-2012 Dik Grapendaal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package sh.grapendaal.tsuushin.permission;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import sh.grapendaal.tsuushin.message.User;

public class PermissionData {
	private User user;
	private User cachedUser;
	private String hashedPassword;
	private Set<Permission> permissions = new HashSet<Permission>();
	private boolean identified;

	public PermissionData(User user) {
		this(user, null);
	}

	public PermissionData(User user, String hashedPassword) {
		this(user, hashedPassword, null, true);
	}

	public PermissionData(User user, String hashedPassword, Collection<Permission> permissions, boolean identified) {
		this.user = user;
		this.hashedPassword = hashedPassword;
		if (permissions != null) {
			this.permissions.addAll(permissions);
		}
		this.identified = identified;
	}

	public User getUser() {
		return user;
	}

	public User getCachedUser() {
		return cachedUser;
	}

	public void setCachedUser(User cachedUser) {
		this.cachedUser = cachedUser;
	}

	public String getHashedPassword() {
		return hashedPassword;
	}

	public Set<Permission> getPermissions() {
		return permissions;
	}

	public boolean grantPermission(Permission permission) {
		return permissions.add(permission);
	}

	public boolean revokePermission(Permission permission) {
		return permissions.remove(permission);
	}

	public boolean hasPermission(Permission permission) {
		return permissions.contains(permission);
	}

	/**
	 * Returns whether the user is currently identified. This will always return
	 * true if this user does not have a password set up.
	 * 
	 * @return Whether the user has identified himself.
	 */
	public boolean isIdentified() {
		if (this.hashedPassword == null) {
			return true;
		}
		return identified;
	}

	public void setIdentified(boolean identified) {
		this.identified = identified;
	}
}
